/*
 * Login / Setup dialog handler.
 *
 * License: LGPL v3
 *
 * Created on Sep 27, 2009, 11:34:19 AM
 */
package org.passwordstore.gui;

import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.passwordstore.Main;
import org.passwordstore.Resource;
import org.passwordstore.util.H2JDBCParser;

/**
 *
 * @author thotheolh
 */
public class LoginDialog extends javax.swing.JDialog {

    private boolean proceed;
    private Main mainInst;

    /** Creates new form LoginDialog */
    public LoginDialog(java.awt.Frame parent, boolean modal, Main mainInstance) {
        super(parent, modal);
        initComponents();
        int width = 300;
        int height = 133;
        setSize(width, height);
//        Toolkit toolkit = Toolkit.getDefaultToolkit();
//        Dimension screen = toolkit.getScreenSize();
//        int locHeight = (int) ((screen.getHeight() - height) / 2);
//        int locWidth = (int) ((screen.getWidth() - width) / 2);
//        this.setLocation(locWidth, locHeight);
        this.setLocationRelativeTo(null);
        initImageIcon("pwdstore.png");
        this.mainInst = mainInstance;
        this.userTf.grabFocus();
        init();
    }

    public void init() {
        //Adjust look and feel
        this.pack();
        //Check if database has been setup
        H2JDBCParser h2temp = new H2JDBCParser(Resource.getInstance().processConnPath(Resource.getInstance().getSystem().getProperty("db.connection").toString()));
        File temp = new File(h2temp.getBaseDir() + "/" + h2temp.getDbName() + ".h2.db");
        if (!temp.exists()) {
            setTitle("PasswordStore - Setup");
            JOptionPane.showMessageDialog(this, "Please enter your choice of username and password to create a new account.", "Setup Account", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public boolean doLogin(String username, String inpass) {
        String password = inpass + " " + inpass;
        //System.out.println("Getting db path properties...");//Diagnostics
        String dbpath = Resource.getInstance().getSystem().getProperty("db.connection").toString();
        //System.out.println("DB Path: "+dbpath);//Diagnostics
        Resource.getInstance().initDBConn(dbpath, username, password);
        if (Resource.getInstance().getSql().getConn() != null) {
            Resource.getInstance().setUsername(username);
            Resource.getInstance().setPassword(password.toCharArray());
            password = new String();
            inpass = new String();
            setTitle("PasswordStore - Login");
            return true;
        }
        password = new String();
        inpass = new String();
        setTitle("PasswordStore - Login");
        return false;
    }

    /**
     * Clear and reset fields
     */
    public void clear() {
        this.userTf.setText("");
        this.pwdTf.setText("");
        this.userTf.grabFocus();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        contentPane = new javax.swing.JPanel();
        usrLbl = new javax.swing.JLabel();
        pwdLbl = new javax.swing.JLabel();
        userTf = new javax.swing.JTextField();
        pwdTf = new javax.swing.JPasswordField();
        bottomPane = new javax.swing.JPanel();
        buttonPane = new javax.swing.JPanel();
        clearBtn = new javax.swing.JButton();
        submitBtn = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("PasswordStore - Login");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        usrLbl.setText("Username: ");

        pwdLbl.setText("Password: ");

        userTf.setColumns(15);
        userTf.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                userTfKeyPressed(evt);
            }
        });

        pwdTf.setColumns(15);
        pwdTf.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                pwdTfKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout contentPaneLayout = new javax.swing.GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
            contentPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(contentPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(usrLbl)
                    .addComponent(pwdLbl))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(contentPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pwdTf, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
                    .addComponent(userTf, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE))
                .addContainerGap())
        );
        contentPaneLayout.setVerticalGroup(
            contentPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(contentPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usrLbl)
                    .addComponent(userTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(contentPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pwdLbl)
                    .addComponent(pwdTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(contentPane, java.awt.BorderLayout.CENTER);

        bottomPane.setLayout(new java.awt.BorderLayout());

        clearBtn.setText("Clear");
        clearBtn.setToolTipText("Clear the username and password");
        clearBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearBtnActionPerformed(evt);
            }
        });
        buttonPane.add(clearBtn);

        submitBtn.setText("Submit");
        submitBtn.setToolTipText("Login to PasswordStore");
        submitBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitBtnActionPerformed(evt);
            }
        });
        buttonPane.add(submitBtn);

        bottomPane.add(buttonPane, java.awt.BorderLayout.EAST);

        jLabel1.setForeground(new java.awt.Color(255, 0, 0));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("Password must be 8 characters long or more ! ");
        bottomPane.add(jLabel1, java.awt.BorderLayout.PAGE_START);

        getContentPane().add(bottomPane, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clearBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearBtnActionPerformed
        // TODO add your handling code here:
        clear();
    }//GEN-LAST:event_clearBtnActionPerformed

    private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitBtnActionPerformed
        // TODO add your handling code here:
        char[] passchar = this.pwdTf.getPassword();
        String password = new String(passchar);
        if (passchar.length >= 8) {
            //If is lock screen, unlock screen. Else normal login
            if (Resource.getInstance().getMainInstance().isIsLocked()) {
                //System.out.println("Detected locked window...");//diagnostics
                if (Resource.getInstance().getMainInstance().getMf() != null) {
                    //System.out.println("Unlocking window...");//diagnostics
                    if (doLogin(this.userTf.getText(), password)) {
                        Resource.getInstance().getMainInstance().getMf().doUnlockWindow();
                        clear();
                        password = new String();
                        Resource.getInstance().clearLoginPassword(passchar);
                        //System.out.println("Window unlocked...");//diagnostics
                    } else {
                        clear();
                        password = new String();
                        Resource.getInstance().clearLoginPassword(passchar);
                        JOptionPane.showMessageDialog(this, "Wrong password/username !", "Bad Login", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                if (doLogin(this.userTf.getText(), password)) {
                    Resource.getInstance().setMainInstance(mainInst);
                    mainInst.spawnMainWindow();
                    clear();
                    password = new String();
                    Resource.getInstance().clearLoginPassword(passchar);
                    mainInst.setLogin(this);
                    this.dispose();
                } else {
                    clear();
                    password = new String();
                    Resource.getInstance().clearLoginPassword(passchar);
                    JOptionPane.showMessageDialog(this, "Wrong password/username !", "Bad Login", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "Password must be 8 character long or more !", "Short password", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_submitBtnActionPerformed

    private void pwdTfKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pwdTfKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.submitBtnActionPerformed(null);
        }
    }//GEN-LAST:event_pwdTfKeyPressed

    private void userTfKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_userTfKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            pwdTf.grabFocus();
        }
    }//GEN-LAST:event_userTfKeyPressed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        if (Resource.getInstance().getMainInstance().isIsLocked()) {
            if (Resource.getInstance().getMainInstance().getMf().getTrayIcon() == null) {
                int numOpt = JOptionPane.showConfirmDialog(this, "PasswordStore is in Lock Window mode.\nAre you sure you want to exit PasswordStore ?", "Exit PasswordStore", JOptionPane.YES_NO_OPTION);
                if (numOpt == JOptionPane.YES_OPTION) {
                    Resource.getInstance().clearLoginPassword(pwdTf.getPassword());
                    Resource.getInstance().shutdown();
                }
            } else {
            }
        } else {
            Resource.getInstance().shutdown();
        }
    }//GEN-LAST:event_formWindowClosing
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel bottomPane;
    private javax.swing.JPanel buttonPane;
    private javax.swing.JButton clearBtn;
    private javax.swing.JPanel contentPane;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel pwdLbl;
    private javax.swing.JPasswordField pwdTf;
    private javax.swing.JButton submitBtn;
    private javax.swing.JTextField userTf;
    private javax.swing.JLabel usrLbl;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the proceed
     */
    public boolean isProceed() {
        return proceed;
    }

    /**
     * Indicator for login to indicate whether to proceed to main window (only if successfully login)
     * @param boolean
     */
    public void setProceed(boolean proceed) {
        this.proceed = proceed;
    }

    private void initImageIcon(String image) {
        if (new File(image).exists()) {
            this.setIconImage(new ImageIcon(image).getImage());
        } else {
            JOptionPane.showMessageDialog(null, "Image icon not found !", "No Icon", JOptionPane.WARNING_MESSAGE);
        }
    }

    public void prepTextField() {
        userTf.grabFocus();
    }
}
